﻿using System.Collections.Generic;
using System.Linq;
using System.Threading;
using TK.FreeSqlExtension;

namespace FreeSql
{
    /// <summary>
    /// IFreeSqlFactory
    /// </summary>
    public interface IFreeSqlFactory
    {
        /// <summary>
        /// 分库分表信息
        /// </summary>
        AsyncLocal<SplitInfo> SplitInfo { get; }

        /// <summary>
        /// 根据dbKey获取IFreeSql
        /// </summary>
        /// <param name="dbKey">连接唯一标识</param>
        IFreeSql GetFreeSql(string dbKey);

        /// <summary>
        /// 获取当前线程IFreeSql
        /// </summary>
        IFreeSql GetFreeSql();
    }

    /// <summary>
    /// FreeSqlFactory
    /// </summary>
    public class FreeSqlFactory : IFreeSqlFactory
    {
        private readonly IList<IFreeSqlClient> _freeSqlClientList;

        /// <summary>
        /// ctor
        /// </summary>
        public FreeSqlFactory(IEnumerable<IFreeSqlClient> freeSqlClientList)
        {
            _freeSqlClientList = freeSqlClientList.ToList();
            SplitInfo = new AsyncLocal<SplitInfo>();
        }

        /// <summary>
        /// 分库分表信息
        /// </summary>
        public AsyncLocal<SplitInfo> SplitInfo { get; }

        /// <summary>
        /// 根据dbKey获取IFreeSql,未匹配返回null
        /// </summary>
        /// <param name="dbKey">连接唯一标识</param>
        public IFreeSql GetFreeSql(string dbKey)
        {
            return _freeSqlClientList.FirstOrDefault(m => m.DbKey == dbKey)?.FreeSql;
        }

        /// <summary>
        /// 获取当前线程IFreeSql
        /// </summary>
        public IFreeSql GetFreeSql()
        {
            var dbkey = string.IsNullOrWhiteSpace(SplitInfo.Value?.DbKey) ? _freeSqlClientList[0].DbKey : SplitInfo.Value?.DbKey;
            return _freeSqlClientList.FirstOrDefault(m => m.DbKey == dbkey).FreeSql;
        }
    }
}
